package luj.tool.jnproxyan.framework.lujnet.receive;

import io.netty.buffer.ByteBuf;
import luj.bean.api.BeanContext;
import luj.net.api.server.FrameDataReceiver;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import luj.tool.jnproxyan.proxy.network.socks.cmd.connect.CmdConnectHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.google.common.base.Preconditions.checkState;

@Component
final class Recv45RequestPort implements FrameDataReceiver {

  @Override
  public Result receive(Context ctx) throws Exception {
    ConnState connState = ctx.getConnectionState();
    ByteBuf frameBuf = ctx.getLastFrame();

    int port = frameBuf.readShort();
    connState.setDstPort(port);

    int cmd = connState.getCmd();
    checkState(cmd == CONNECT, cmd);
//    LOG.debug("cmd: {}", cmd);

    FrameDataReceiver c2pReceiver = new CmdConnectHandler(connState, _lujbean).handle();

    return ctx.then()
//        .waitBytes(Integer.MAX_VALUE)
        .nextReceiver(c2pReceiver);
  }

  private static final Logger LOG = LoggerFactory.getLogger(Recv45RequestPort.class);

  private static final int CONNECT = 0x01;

  @Autowired
  BeanContext _lujbean;
}
